import { requestClient, baseRequestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';

export namespace AdminInvoiceApi {
  export interface InvoiceRecord {
    id: string;
    invoice_number: string;
    tenant_id: number;
    landing_company_id: number;
    invoice_amount: number;
    billing_type: string;
    billing_type_display: string;
    billing_category: string;
    billing_category_display?: string;
    invoice_title: string;
    tax_number: string;
    status: string;
    status_display: string;
    invoice_remarks?: string | null;
    rejection_reason?: string | null;
    invoice_file_path?: string | null;
    express_tracking_number?: string | null;
    application_time: string;
    processed_at?: string | null;
    issued_at?: string | null;
    tenant?: {
      id: number | string;
      name: string;
      company_name?: string | null;
    } | null;
    landing_company?: {
      id: number;
      name: string;
      short_name?: string | null;
    } | null;
  }

  export interface InvoiceListResponse {
    items: InvoiceRecord[];
    pagination: {
      total: number;
      per_page: number;
      current_page: number;
      last_page: number;
    };
  }

  export interface ListParams {
    page?: number;
    per_page?: number;
    status?: string | string[];
    tenant_keyword?: string;
    landing_company_id?: number;
    sort_by?: string;
    sort_order?: 'asc' | 'desc';
  }

  export interface StatusOption {
    value: string;
    label: string;
  }
}

export function getAdminInvoices(params: AdminInvoiceApi.ListParams = {}) {
  return requestClient.get<AdminInvoiceApi.InvoiceListResponse>('/api/admin/invoices', {
    params,
  });
}

export function getAdminInvoiceStatusOptions() {
  return requestClient.get<AdminInvoiceApi.StatusOption[]>('/api/admin/invoices/status-options');
}

export function acceptInvoice(invoiceId: string | number) {
  return requestClient.post(`/api/admin/invoices/${invoiceId}/accept`);
}

export function rejectInvoice(invoiceId: string | number, reason: string) {
  return requestClient.post(`/api/admin/invoices/${invoiceId}/reject`, { reason });
}

export function uploadInvoiceFile(invoiceId: string | number, payload: FormData) {
  return requestClient.post(`/api/admin/invoices/${invoiceId}/upload`, payload, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
}

export function voidInvoice(invoiceId: string | number) {
  return requestClient.post(`/api/admin/invoices/${invoiceId}/void`);
}

export async function previewInvoiceFile(invoiceId: string | number) {
  const accessStore = useAccessStore();
  const token = accessStore.accessToken;

  const response = await baseRequestClient.get(`/api/admin/invoices/${invoiceId}/preview`, {
    responseType: 'blob',
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
  });

  return response.data as Blob;
}
